package com.dawn.anypossible.base.auth;

import com.dawn.anypossible.base.route.RoutingDelegate;
import com.dawn.anypossible.base.user.UserRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import java.time.Duration;

/**
 * @author: huangxz
 * @Date: 14:17 2024-2-26
 * @Description:
 */

@RestController
public class TestController {

    @Autowired
    private RoutingDelegate routingDelegate;

    @Autowired
    private UserRepository repository;

    @RequestMapping(value = "/aiproxy/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE}, produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE, MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<String> test(HttpServletRequest request, HttpServletResponse response) {
        var a = """
                测试""";
        System.out.println(a);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication.getPrincipal());
        return routingDelegate.redirect(request, response, "http://localhost:8000", "/aiproxy");
    }

    @PostMapping("/user")
    public void createUser(UserCreateDto userCreateDto) {
        MockDbUser.addUser(userCreateDto.username(), userCreateDto.password());
        System.out.println(userCreateDto);
    }

    @GetMapping("/resource")
    public ResponseEntity<String> getResource(WebRequest request) {

        String etag = "123"; // 自定义方法来生成 ETag
        if (request.checkNotModified(etag)) {
            return null;
        }
        return ResponseEntity
                .ok()
                .eTag(etag) // 设置 ETag 头
                .cacheControl(CacheControl.maxAge(Duration.ofSeconds(30)))
                .body("resource");
    }

    @GetMapping("/test")
    public String test() {

        return "test";
    }
}
